
const { WebSocketServer } = require('ws');
const wss = new WebSocketServer({ port: 8080 });
//启动成功打印
if(wss){
    console.log('server is running');
}
wss.on('connection',function connection(ws){
    let welcome=JSON.stringify({
        type: 'welcome',
        message: '欢迎来到妙手医生极速问诊'
    });
    ws.send(welcome,{binary:false});
    ws.on("error",console.error)
    ws.on("message", async function message(data){
        const message=JSON.parse(data);
        switch(message.type){
            case'init':
            if(message.userId){
                ws.userId=message.userId;
                keeplatestOnlineList("online",message);
            }
            break;
            case 'message':
                wss.clients.forEach(function each(client) {
                    if(client.readystate===Websocket.OPEN){
                        client.send(JSON.stringify(message),{binary:false});
                    }
                })
            break;
            default:
                break;
        }
    })
    ws.on("close",function(){
        keeplatestOnlineList("close",{userId:ws.userId});
    })
})
function keeplatestOnlineList(type,message){
    let index=onlineList.findIndex((item)=>item.userId===message.userId);
    switch(type){
        case "online":
            if(index===-1){
                onlineList.push({
                    userId:message.userId,
                    time:new Date().getTime()
                });
            }
            break;
        case "close":
            if(index!==-1){
                onlineList.splice(index,1);
            }
            break;
        default:
            break;
    }
}